<template>
	<view>
		<login-shell ref="shell" after="afterLogin"></login-shell>
		<view class="root" v-if="loaded">
			<view class="item-blogs">
				<!-- 博客标题 -->
				<p class="item-title">
					<!-- 博客作者头像 -->
					<image :src="host+avatar" alt="" class="item-head"></image>
					<!-- 博客标题 -->
					<span style="border-bottom: 2px solid #8f8f94;width: 100%;">{{blog.title}}</span>
					<span class="iconfont icon-shoucang img-oper" @click.stop="popSheet(blog.id)"></span>
				</p>
				<p style="margin-left: 40rpx; font-size: 10px; color: #8f8f94;">
					<span>{{nickName}}</span>@<span>{{blog.createTime}}</span>
				</p>
				<rich-text :nodes="blog.content"></rich-text>
				<!-- 博客分类 -->
				<p>{{blog.category}}</p>
				<!-- 博客图片 -->
				<image :src="host+blog.picture" mode="aspectFit" style="width: 100%;"></image>
				<p>
					<!-- 博客标签，使用 v-for 遍历标签数组 -->
					<span v-for="tag in blog.tags" class="item-tag">{{tag}}</span>
				</p>
				<view class="item-icon">
					<!-- 博客点赞数 -->
					<span @click.stop="onGoods(blog.id,true)" v-if="!hasGood" class="iconfont icon-dianzan"></span>
					<span @click.stop="onGoods(blog.id,false)" v-else class="iconfont icon-liked"></span>
					<span class="item-desc">{{blog.good}}</span>
					<!-- 博客评论数 -->
					<span class="iconfont icon-pinglun"></span>
					<span class="item-desc">{{comments.length}}</span>
					<!-- 博客阅读数 -->
					<span class="iconfont icon-view"></span>
					<span class="item-desc">{{blog.readCount}}</span>
				</view>
			</view>
			<view style="background: #d3d3d9;height: 1rpx;"></view>
			<view style="margin: 15rpx;"> <text>评论区</text> </view>
			<view class="comment" v-if="hasComment">
				<view v-for="(item,index) in parents" :key="index">
					<view class="parents" @click="clickName(item)">
						<view class="head">
							<view>
								<image :src="item.avatar" mode="" class="item-head"></image>
							</view>
							<view class="name">
								<text class="comment_size">{{item.nickName}}</text>
								<text class="comment_time">{{item.createTime}}</text>
							</view>
						</view>
						<view class="parents_content">
							<text class="comment_size" style="color: black !important; margin-left: 0 !important;"
								@longtap="onLongPress(item.id,item.avatar)">{{item.content}}</text>
						</view>
					</view>
					<view class="repies" v-if="replies[index].length>0">
						<view v-for="(child,i) in replies[index]" :key="i" @click="clickName(child)">
							<view class="head">
								<view class="name">
									<text comment_size>
										<text class="repies_bule">{{child.nickName}}</text>
										<text v-if="item.id != child.parentId">
											<text style="font-size: 20rpx;">回复</text>
											<text class="repies_bule">{{child.toUser}}</text>
										</text>
										<text style="font-size: 20rpx;">:</text>
										<text class="comment_repies_content"
											@longtap="onLongPress(child.id,child.avatar)">{{child.content}}</text>
									</text>
								</view>
							</view>
						</view>
					</view>
					<view style="background: #f1f1f8;height: 1rpx;"></view>
					<view v-if="index==parents.length -1" style="margin-top:50rpx; margin-left: 200rpx;">
						<text class="iconfont icon-daodile" style="font-size: 50rpx;"></text>
					</view>
				</view>
			</view>
			<view v-else style="margin: auto;">
				<image src="../../static/icons/shafa.png"></image>
				<p style="text-align: center;">还没有评论哦，快来抢占沙发吧~</p>
			</view>
			<view style="height: 100rpx;"></view>
			<view class="input">
				<view class="box">
					<textarea @focus="isLogin()" v-model="cmtContent" class="value" maxlength="200"
						:placeholder=placeholder />
					<text class="iconfont icon-paperPlane icon11" @click="postComment()"></text>
				</view>

			</view>
		</view>
	</view>


</template>

<script>
	let parentId = null
	let parent = null
	let cmtUser = null
	let token = null
	export default {
		data() {
			return {
				id: "",
				blog: {},
				host: this.$params.host,
				avatar: '',
				userId: "",
				comments: [],
				nickName: '',
				loaded: false,
				parents: [],
				replies: [],
				hasComment: false,
				hasGood: false,
				placeholder: "请先登录再评论",
				is_owner: false,
				cmtContent: ""
			}
		},
		onLoad(options) {
			console.log(this.blog);
			this.$notification.addNotification(this.$params.noti_refresh_user, this.notificationRefreshUser, this)
			this.$globalData.userInfo = uni.getStorageSync(this.$params.user)
			if (this.$globalData.userInfo != null) {
				cmtUser = this.$globalData.userInfo
				token = cmtUser.token;
			}
			this.placeholder = (token == null ? "请先登录再评论" : "评论千万条,等你发一条");
			this.id = options.id;
			let goods = uni.getStorageSync(this.$params.key_goods);
			this.addReadCount(this.id);
			if (goods) {
				this.hasGood = goods.indexOf(this.id) >= 0
			}

		},
		onUnload() {
			this.$notification.removeNotification(this.$params.noti_refresh_user, this)
		},

		methods: {
			refreshComment(id, comments) {
				this.$notification.postNotification(this.$params.noti_refresh_comment, {
					id,
					comments,
				})
			},
			onLongPress(id, name) {
				uni.showModal({
					title: '提示',
					content: '是否删除该评论',
					success: res => {
						if (res.confirm) {
							this.deleteComment(id, name)
						} else if (res.cancel) {
							return
						}

					},
					fail: () => {},
					complete: () => {}
				})
			},
			deleteComment(id, avatar) {
				if (this.host + cmtUser.avatar != avatar) {
					uni.showToast({
						title: '没有权限',
						icon: 'error',
					})
					return
				}
				let data = {
					"token": token
				}
				this.$request.deleteParams(this.host + '/api/v1/blogs/comments/delete/' + id, data, res => {
					this.getBlog(this.id)
					uni.showToast({
						title: '删除成功',
						icon: 'success',
					})

				}, () => {}, () => {})
			},
			isLogin() {
				if (token == null) {
					this.placeholder = "请先登录再评论";
					uni.showToast({
						title: '请先登录后再评论',
						icon: 'error',
					})
					this.$refs.shell.show()
				} else {
					if (parentId == null) {
						this.placeholder = "评论千万条,等你发一条";
					} else {
						this.placeholder = "回复" + parent.nickName
					}

				}
			},
			notificationRefreshUser(info) {
				cmtUser = info;
				token = info.token
				this.isLogin()

			},
			postComment() {
				if (this.userId == cmtUser.id) {
					this.is_owner = true
				}
				let data = {
					"avatar": "/" + cmtUser.avatar,
					"blog_id": this.id,
					"content": this.cmtContent,
					"email": cmtUser.email,
					"is_owner": this.is_owner,
					"nick_name": cmtUser.nickName,
					"parent_id": parentId,
					"token": token
				}
				if (this.cmtContent.length <= 0) {
					uni.showToast({
						title: '输入内容不能为空',
						icon: 'error',
					})
					return
				} else {
					this.$request.post(this.host + 'api/v1/blogs/comment', data, res => {
						if (res.success == false) {
							uni.showToast({
								title: res.message,
								icon: 'error',
							})
							uni.removeStorageSync(this.$params.user)
							this.$globalData.userInfo == {};
							cmtUser = this.$globalData.userInfo;
							token = null
							this.isLogin()
							this.cmtContent = ""
						}
						this.cmtContent = ""
						this.getBlog(this.id)
						this.refreshComment(this.id, this.comments)
						parentId = null
						this.placeholder = "评论千万条,等你发一条";

					}, () => {}, () => {})
				}

			},

			addReadCount(id) {
				let data = {
					"id": id
				}
				this.$request.postParams(this.host + 'api/v1/blogs/read', data, res => {
					let count = res.data
					this.$notification.postNotification(this.$params.noti_refresh_count, {
						id,
						count,
					})
				}, () => {}, () => {
					this.getBlog(id)
				})
			},
			getBlog(id) {
				this.$request.get(this.host + 'api/v1/blogs/' + id, res => {
					this.blog = res.data
					this.avatar = res.data.user.avatar
					this.comments = res.data.comments
					this.hasComment = this.comments.length
					this.nickName = res.data.user.nickName
					this.userId = res.data.user.id
					this.blog.content = this.blog.content.replace(/\<img/gi, '<img class="img" ')
					this.blog.createTime = this.$util.formaTime(new Date(this.blog.createTime))
					this.loaded = true
					this.formatComments(this.comments)
					uni.setNavigationBarTitle({
						title: this.nickName
					})
					if (this.comments.length > 0) {
						this.refreshComment(this.id, this.comments)
					}
					console.log(this.blog);
					let count = this.comments.length
					let id = this.blog.id
				}, () => {}, () => {})
			},
			formatComments(comments) {
				// 如果评论数组为空，则直接返回
				if (comments.length == 0) {
					return
				}
				// 存储根评论的数组
				let rootComments = []
				// 遍历所有评论，为评论添加格式化后的时间，同时将根评论添加到 rootComments 中
				comments.forEach(comment => {
					if (comment.avatar.startsWith('/')) {
						comment.avatar = comment.avatar.substring(1)
					}
					if (!comment.avatar.startsWith('http')) {
						comment.avatar = this.$params.host + comment.avatar;
					}
					// 格式化评论时间
					comment.createTime = this.$util.formaTime(new Date(comment.createTime))
					// 如果 parentId 为 null，则说明该评论为根评论
					if (comment.parentId == null) {
						rootComments.push(comment)
					}
				})
				// 存储所有回复评论的数组，长度为 rootComments 的长度
				rootComments.sort((c1, c2) => {
					return new Date(c2.createTime) - new Date(c1.createTime)
				})
				let replies = new Array(rootComments.length).fill([])
				let index = 0
				// 遍历根评论数组，获取每个根评论的子评论并存储到 replies 数组中
				rootComments.forEach(rootComment => {
					// 获取根评论的子评论
					const children = this.getChildren(rootComment, comments)
					// 存储到 replies 数组中
					replies[index] = children
					index++
				})
				// 将根评论和回复评论存储到 data 中
				this.parents = rootComments
				this.replies = replies
			},

			getChildren(parent, comments) {
				// 如果 parent 为空，则返回空数组
				if (!parent) {
					return []
				}
				// 存储子评论的数组
				const children = []
				comments.forEach(comment => {
					// 如果该评论未被使用过且 parentId 与 parent.id 相同，则说明该评论为 parent 的子评论
					if (!comment.used && comment.parentId === parent.id) {
						// 将该评论添加到 children 中
						children.push(comment)
						comment.toUser = parent.nickName
						// 将该评论标记为已使用
						comment.used = true
						// 递归获取该评论的子评论，并添加到 children 中
						children.push(...this.getChildren(comment, comments))
					}
				})
				return children
			},
			clickName(item) {
				if (token == null) {
					this.$refs.shell.show()
				} else {
					this.placeholder = "回复" + item.nickName
					parent = item

					parentId = item.id
				}

			},
			onGoods(id, isGood) {
				// 设置请求头
				let header = {
					"accept": "aplication/json, */*;q=0.1",
					'Content-Type': this.$params.form_data
				};
				// 设置请求数据
				let data = {
					'id': id
				};
				// 设置请求地址
				let url = this.host + (isGood ? 'api/v1/blogs/good' : 'api/v1/blogs/delgood');
				// 发送POST请求
				this.$request.postWithHeader(url, header, data, res => {

					if (isGood) {
						// 从缓存中获取数组
						let cacheArray = uni.getStorageSync(this.$params.key_goods) || []

						// 将 id 添加到数组中
						cacheArray.push(id)

						// 将更新后的数组存回缓存中
						uni.setStorageSync(this.$params.key_goods, cacheArray)

						this.hasGood = true
					} else {
						// 如果是取消点赞操作，将博客ID从点赞列表中移除
						let cacheArray = uni.getStorageSync(this.$params.key_goods) || []

						let index = cacheArray.indexOf(id)

						if (index !== -1) {
							cacheArray.splice(index, 1)
							uni.setStorageSync(this.$params.key_goods, cacheArray)
						}
						this.hasGood = false
					}
					// 更新博客的点赞数
					this.blog.good = res.data

					let good = res.data
					
					this.$notification.postNotification(this.$params.noti_refresh_good, {
						id,
						good,
					})

				}, () => {}, () => {})


			},
			popSheet(id) {
				uni.showActionSheet({
					itemList: ["删除", "收藏"],
					success: res => {
						if (res.tapIndex == 0) {
							uni.showModal({
								title: '删除',
								content: '你确认删除吗',
								showCancel: true,
								cancelText: '取消',
								confirmText: '删除',
								success: res => {
									if (res.confirm) this.deleteBlog(id)
								},
								fail: () => {},
								complete: () => {}
							});
						} else if (res.tapIndex == 1) {
							uni.showToast({
								title: "已收藏"
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
		}
	}
</script>

<style>
	@import url(blog.css);
	@import url('../../common/typo.css');
</style>